<template>
  <div class="doctor-medical-orders">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <div class="header-info">
            <h2>关联医嘱查看</h2>
            <div class="breadcrumb-info" v-if="queryParams.patientName">
              <span>患者：{{ queryParams.patientName }}</span>
              <span v-if="queryParams.recordDate">就诊日期：{{ formatDate(queryParams.recordDate) }}</span>
            </div>
          </div>
          <div class="header-actions">
            <el-button @click="goBack">
              <el-icon><ArrowLeft /></el-icon> 返回
            </el-button>
            <el-button type="primary" @click="refreshData">
              <el-icon><Refresh /></el-icon> 刷新
            </el-button>
          </div>
        </div>
      </template>
      
      <!-- 医嘱列表 -->
      <div v-loading="loading">
        <div v-if="medicalOrdersList.length === 0" class="empty-state">
          <el-empty description="暂无关联医嘱数据" />
        </div>
        
        <div v-else>
          <div v-for="(order, index) in medicalOrdersList" :key="order.id || order._id" class="medical-order-wrapper">
            <!-- 医嘱卡片 -->
            <el-card class="medical-order-card" style="margin-bottom: 25px;">
              <template #header>
                <div class="medical-order-header">
                  <div class="header-left">
                    <h3>医嘱 {{ index + 1 }}</h3>
                    <el-tag :type="getOrderTypeTag(order.type)" size="default" class="type-tag">
                      {{ getOrderTypeText(order.type) }}
                    </el-tag>
                    <el-tag :type="getStatusTypeTag(order.status)" size="default" class="status-tag">
                      {{ getStatusText(order.status) }}
                    </el-tag>
                    <el-tag :type="getPriorityTag(order.priority)" size="default" class="priority-tag" v-if="order.priority">
                      {{ order.priority }}
                    </el-tag>
                  </div>
                  <div class="header-right">
                    <span class="order-id">医嘱编号：{{ order.orderId || order.id || order._id }}</span>
                    <span class="created-time">开具时间：{{ formatDate(order.createdAt || order.createTime) }}</span>
                  </div>
                </div>
              </template>
              
              <div class="medical-order-content">
                <!-- 基本信息区域 -->
                <div class="info-section">
                  <h4 class="section-title">
                    <el-icon><UserFilled /></el-icon>
                    基本信息
                  </h4>
                  <el-descriptions :column="3" border>
                    <el-descriptions-item label="开具医生" label-class-name="desc-label">
                      {{ order.doctorName || '未知' }}
                    </el-descriptions-item>
                    <el-descriptions-item label="科室" label-class-name="desc-label">
                      {{ order.departmentName || '未知' }}
                    </el-descriptions-item>
                    <el-descriptions-item label="医嘱状态" label-class-name="desc-label">
                      <el-tag :type="getStatusTypeTag(order.status)" size="small">
                        {{ getStatusText(order.status) }}
                      </el-tag>
                    </el-descriptions-item>
                    <el-descriptions-item label="医嘱类型" label-class-name="desc-label">
                      {{ order.type || '未标明' }}
                    </el-descriptions-item>
                    <el-descriptions-item label="优先级" label-class-name="desc-label">
                      <el-tag :type="getPriorityTag(order.priority)" size="small" v-if="order.priority">
                        {{ order.priority }}
                      </el-tag>
                      <span v-else>常规</span>
                    </el-descriptions-item>
                    <el-descriptions-item label="执行频次" label-class-name="desc-label">
                      {{ order.frequency || '未标明' }}
                    </el-descriptions-item>
                  </el-descriptions>
                </div>
                
                <!-- 医嘱项目区域 -->
                <div class="info-section">
                  <h4 class="section-title">
                    <el-icon><List /></el-icon>
                    医嘱项目
                  </h4>
                  
                  <div v-if="order.items && order.items.length > 0" class="order-items-list">
                    <div v-for="(item, itemIndex) in order.items" :key="itemIndex" class="order-item">
                      <div class="order-item-header">
                        <span class="item-number">项目 {{ itemIndex + 1 }}</span>
                        <el-tag :type="getOrderTypeTag(item.type)" size="small" class="item-type-tag">
                          {{ getOrderTypeText(item.type) }}
                        </el-tag>
                      </div>
                      
                      <el-descriptions :column="2" border class="order-item-details">
                        <el-descriptions-item label="项目类型" label-class-name="item-label">
                          <span class="item-type">{{ getOrderTypeText(item.type) }}</span>
                        </el-descriptions-item>
                        <el-descriptions-item label="执行频次" label-class-name="item-label">
                          <span class="frequency">{{ item.frequency || '未标明' }}</span>
                        </el-descriptions-item>
                        <el-descriptions-item label="持续时间" label-class-name="item-label">
                          <span class="duration">{{ item.duration || '未标明' }}</span>
                        </el-descriptions-item>
                        <el-descriptions-item label="项目备注" label-class-name="item-label" v-if="item.note">
                          <span class="item-note">{{ item.note }}</span>
                        </el-descriptions-item>
                        <el-descriptions-item label="医嘱内容" :span="2" label-class-name="item-label">
                          <div class="order-content">
                            {{ item.content || '无具体内容' }}
                          </div>
                        </el-descriptions-item>
                      </el-descriptions>
                    </div>
                  </div>
                  
                  <!-- 单个医嘱的内容显示（兼容旧数据格式） -->
                  <div v-else-if="order.content" class="single-order-content">
                    <el-descriptions :column="2" border>
                      <el-descriptions-item label="医嘱内容" :span="2" label-class-name="item-label">
                        <div class="order-content">
                          {{ order.content }}
                        </div>
                      </el-descriptions-item>
                      <el-descriptions-item label="执行时长" label-class-name="item-label" v-if="order.duration">
                        <span class="duration">{{ order.duration }}</span>
                      </el-descriptions-item>
                      <el-descriptions-item label="备注说明" label-class-name="item-label" v-if="order.instructions">
                        <span class="instructions">{{ order.instructions }}</span>
                      </el-descriptions-item>
                    </el-descriptions>
                  </div>
                  
                  <div v-else class="no-order-items">
                    <el-empty description="暂无医嘱项目信息" :image-size="60" />
                  </div>
                </div>
                
                <!-- 执行信息区域 -->
                <div class="info-section" v-if="order.execution">
                  <h4 class="section-title">
                    <el-icon><Clock /></el-icon>
                    执行信息
                  </h4>
                  <el-descriptions :column="2" border>
                    <el-descriptions-item label="执行状态" label-class-name="desc-label">
                      <el-tag :type="getStatusTypeTag(order.execution.status)" size="small">
                        {{ getStatusText(order.execution.status) }}
                      </el-tag>
                    </el-descriptions-item>
                    <el-descriptions-item label="执行人员" label-class-name="desc-label">
                      {{ order.execution.executedByName || order.execution.executedBy || '未指定' }}
                    </el-descriptions-item>
                    <el-descriptions-item label="计划执行时间" label-class-name="desc-label" v-if="order.execution.scheduledTime">
                      {{ formatDate(order.execution.scheduledTime) }}
                    </el-descriptions-item>
                    <el-descriptions-item label="实际执行时间" label-class-name="desc-label" v-if="order.execution.executedAt">
                      {{ formatDate(order.execution.executedAt) }}
                    </el-descriptions-item>
                    <el-descriptions-item label="执行备注" :span="2" label-class-name="desc-label" v-if="order.execution.notes">
                      <span class="execution-notes">{{ order.execution.notes }}</span>
                    </el-descriptions-item>
                  </el-descriptions>
                </div>
                
                <!-- 整体医嘱说明区域 -->
                <div class="info-section" v-if="order.note">
                  <h4 class="section-title">
                    <el-icon><EditPen /></el-icon>
                    医嘱说明
                  </h4>
                  <div class="notes-content">
                    <p>{{ order.note }}</p>
                  </div>
                </div>
                
                <!-- 操作按钮 -->
                <div class="action-section">
                  <el-button type="primary" @click="printMedicalOrder(order)" plain>
                    <el-icon><Printer /></el-icon>
                    打印医嘱
                  </el-button>
                </div>
              </div>
            </el-card>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { medicalRecordAPI, doctorAPI, departmentAPI } from '@/utils/api'
import { formatDate } from '@/utils/date'
import { ArrowLeft, Refresh, Clock, UserFilled, List, EditPen, Printer } from '@element-plus/icons-vue'

// 路由实例
const router = useRouter()
const route = useRoute()

// 数据状态
const loading = ref(false)
const medicalOrdersList = ref([])

// 查询参数
const queryParams = reactive({
  medicalRecordId: route.query.medicalRecordId || '',
  patientName: route.query.patientName || '',
  recordDate: route.query.recordDate || ''
})

// 获取医嘱类型标签颜色
const getOrderTypeTag = (type) => {
  const typeMap = {
    '药品': 'success',
    '检验': 'warning',
    '检查': 'warning',
    '治疗': 'primary',
    '护理': 'info',
    '饮食': 'success',
    '其他': 'info',
    'medication': 'success',
    'treatment': 'primary',
    'examination': 'warning',
    'nursing': 'info',
    'diet': 'success',
    'activity': 'primary',
    'other': 'info'
  }
  return typeMap[type] || 'info'
}

// 获取医嘱类型文本
const getOrderTypeText = (type) => {
  const typeMap = {
    '药品': '药品医嘱',
    '检验': '检验医嘱',
    '检查': '检查医嘱',
    '治疗': '治疗医嘱',
    '护理': '护理医嘱',
    '饮食': '饮食医嘱',
    '其他': '其他医嘱',
    'medication': '用药医嘱',
    'treatment': '治疗医嘱',
    'examination': '检查医嘱',
    'nursing': '护理医嘱',
    'diet': '饮食医嘱',
    'activity': '活动医嘱',
    'other': '其他医嘱'
  }
  return typeMap[type] || type || '未知类型'
}

// 获取状态标签颜色
const getStatusTypeTag = (status) => {
  const statusMap = {
    'pending': 'warning',
    'executing': 'primary', 
    'completed': 'success',
    'cancelled': 'danger',
    'suspended': 'info',
    '待执行': 'warning',
    '执行中': 'primary',
    '已完成': 'success',
    '已取消': 'danger',
    '已暂停': 'info'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    'pending': '待执行',
    'executing': '执行中',
    'completed': '已完成',
    'cancelled': '已取消',
    'suspended': '已暂停'
  }
  return statusMap[status] || status || '未知状态'
}

// 获取优先级标签颜色
const getPriorityTag = (priority) => {
  const priorityMap = {
    '常规': 'info',
    '加急': 'warning',
    '紧急': 'danger'
  }
  return priorityMap[priority] || 'info'
}

// 返回上一页
const goBack = () => {
  router.go(-1)
}

// 刷新数据
const refreshData = () => {
  loadMedicalOrders()
}

// 打印医嘱
const printMedicalOrder = (order) => {
  const printWindow = window.open('', '_blank')
  if (!printWindow) {
    ElMessage.warning('请允许弹出窗口以打印医嘱')
    return
  }
  
  // 构建医嘱项目HTML
  let itemsHtml = ''
  if (order.items && order.items.length > 0) {
    itemsHtml = '<h3>医嘱项目</h3><table border="1" cellspacing="0" cellpadding="8" style="width: 100%; border-collapse: collapse; margin: 15px 0;">'
    itemsHtml += '<tr style="background-color: #f5f7fa;"><th>项目类型</th><th>医嘱内容</th><th>频次</th><th>持续时间</th><th>备注</th></tr>'
    
    order.items.forEach((item, index) => {
      itemsHtml += `<tr>
        <td>${getOrderTypeText(item.type)}</td>
        <td style="max-width: 300px;">${item.content || '-'}</td>
        <td>${item.frequency || '-'}</td>
        <td>${item.duration || '-'}</td>
        <td>${item.note || '-'}</td>
      </tr>`
    })
    itemsHtml += '</table>'
  } else if (order.content) {
    itemsHtml = `<h3>医嘱内容</h3><div style="padding: 15px; background-color: #f9f9f9; border-left: 4px solid #409EFF;">${order.content}</div>`
  }
  
  // 构建打印内容
  const printContent = `
    <html>
      <head>
        <title>医嘱单 - ${queryParams.patientName}</title>
        <style>
          body { font-family: Arial, sans-serif; margin: 20px; line-height: 1.6; }
          h1 { text-align: center; margin-bottom: 20px; color: #333; }
          .header { border-bottom: 2px solid #ddd; padding-bottom: 15px; margin-bottom: 20px; }
          .info-item { margin-bottom: 8px; }
          .label { font-weight: bold; display: inline-block; width: 120px; }
          table { font-size: 14px; width: 100%; }
          th { background-color: #f5f7fa; font-weight: bold; }
          .footer { margin-top: 30px; border-top: 1px solid #ddd; padding-top: 15px; }
          .signature { text-align: right; margin-top: 40px; }
        </style>
      </head>
      <body>
        <h1>医嘱单</h1>
        <div class="header">
          <div class="info-item"><span class="label">患者姓名：</span>${queryParams.patientName}</div>
          <div class="info-item"><span class="label">就诊日期：</span>${formatDate(queryParams.recordDate)}</div>
          <div class="info-item"><span class="label">医嘱编号：</span>${order.orderId || order.id || order._id}</div>
          <div class="info-item"><span class="label">开具时间：</span>${formatDate(order.createdAt)}</div>
          <div class="info-item"><span class="label">医嘱类型：</span>${order.type || '未标明'}</div>
          <div class="info-item"><span class="label">优先级：</span>${order.priority || '常规'}</div>
        </div>
        
        ${itemsHtml}
        
        ${order.note ? `<h3>医嘱说明</h3><div style="padding: 15px; background-color: #fff9e6; border-left: 4px solid #e6a23c;">${order.note}</div>` : ''}
        
        <div class="signature">
          <div>开具医生：__________________</div>
          <div style="margin-top: 10px;">执行护士：__________________</div>
          <div style="margin-top: 10px;">打印时间：${formatDate(new Date())}</div>
        </div>
      </body>
    </html>
  `
  
  printWindow.document.open()
  printWindow.document.write(printContent)
  printWindow.document.close()
  
  setTimeout(() => {
    printWindow.print()
    printWindow.close()
  }, 500)
}

// 查询医生信息
const getDoctorInfo = async (doctorId) => {
  if (!doctorId) return null
  
  try {
    console.log('查询医生信息, ID:', doctorId)
    const res = await doctorAPI.getDoctor(doctorId)
    if (res.success && res.data) {
      console.log('医生查询成功:', res.data)
      return res.data
    }
  } catch (error) {
    console.error('查询医生信息失败:', error)
  }
  return null
}

// 查询科室信息
const getDepartmentInfo = async (departmentId) => {
  if (!departmentId) return null
  
  try {
    console.log('查询科室信息, ID:', departmentId)
    const res = await departmentAPI.getDepartment(departmentId)
    if (res.success && res.data) {
      console.log('科室查询成功:', res.data)
      return res.data
    }
  } catch (error) {
    console.error('查询科室信息失败:', error)
  }
  return null
}

// 填充医生和科室信息
const fillDoctorAndDepartmentInfo = async (medicalOrders) => {
  const doctorCache = new Map()
  const departmentCache = new Map()
  
  for (let order of medicalOrders) {
    // 填充医生信息
    if (order.doctorId && !order.doctorName) {
      if (!doctorCache.has(order.doctorId)) {
        const doctorInfo = await getDoctorInfo(order.doctorId)
        doctorCache.set(order.doctorId, doctorInfo)
      }
      const doctorInfo = doctorCache.get(order.doctorId)
      if (doctorInfo) {
        order.doctorName = doctorInfo.name || '未知医生'
      }
    }
    
    // 填充科室信息
    if (order.departmentId && !order.departmentName) {
      if (!departmentCache.has(order.departmentId)) {
        const departmentInfo = await getDepartmentInfo(order.departmentId)
        departmentCache.set(order.departmentId, departmentInfo)
      }
      const departmentInfo = departmentCache.get(order.departmentId)
      if (departmentInfo) {
        order.departmentName = departmentInfo.name || '未知科室'
      }
    }
  }
  
  return medicalOrders
}

// 加载医嘱数据
const loadMedicalOrders = async () => {
  if (!queryParams.medicalRecordId) {
    ElMessage.error('缺少医疗记录ID参数')
    return
  }
  
  loading.value = true
  
  try {
    const res = await medicalRecordAPI.getRelatedData(queryParams.medicalRecordId)
    
    if (res.success && res.data) {
      let medicalOrders = res.data.medicalOrders?.items || res.data.medical_orders?.items || res.data.medical_orders || []
      
      console.log('医嘱数据加载完成:', medicalOrders)
      
      if (medicalOrders.length > 0) {
        // 填充医生和科室信息
        medicalOrders = await fillDoctorAndDepartmentInfo(medicalOrders)
        console.log('填充医生科室信息后:', medicalOrders)
      }
      
      medicalOrdersList.value = medicalOrders
      
      if (medicalOrdersList.value.length === 0) {
        ElMessage.info('该医疗记录暂无关联医嘱')
      }
    } else {
      ElMessage.error('获取医嘱数据失败')
    }
  } catch (error) {
    console.error('加载医嘱数据失败:', error)
    ElMessage.error('加载医嘱数据失败')
  } finally {
    loading.value = false
  }
}

// 页面加载时获取数据
onMounted(() => {
  loadMedicalOrders()
})
</script>

<style scoped>
.doctor-medical-orders {
  width: 100%;
  overflow-x: auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.header-info h2 {
  margin: 0 0 10px 0;
  color: #303133;
  font-size: 20px;
}

.breadcrumb-info {
  display: flex;
  gap: 20px;
  font-size: 14px;
  color: #606266;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.empty-state {
  padding: 40px 0;
  text-align: center;
}

.medical-order-wrapper {
  margin-bottom: 25px;
}

.medical-order-card {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 12px 0 rgba(0, 0, 0, 0.1);
  border: 1px solid #e4e7ed;
}

.medical-order-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}

.header-left h3 {
  margin: 0;
  color: #303133;
  font-size: 18px;
  font-weight: 600;
}

.type-tag, .status-tag, .priority-tag {
  font-weight: 500;
}

.header-right {
  text-align: right;
  font-size: 14px;
  color: #606266;
  line-height: 1.6;
}

.order-id {
  display: block;
  font-weight: 500;
}

.created-time {
  display: block;
  margin-top: 4px;
}

.medical-order-content {
  padding: 10px 0;
}

.info-section {
  margin-bottom: 25px;
}

.section-title {
  margin: 0 0 15px 0;
  color: #67C23A;
  font-size: 16px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
  border-bottom: 2px solid #67C23A;
  padding-bottom: 8px;
}

:deep(.desc-label) {
  font-weight: 600;
  color: #606266;
}

.order-items-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.order-item {
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  padding: 15px;
  background-color: #fafafa;
}

.order-item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e4e7ed;
}

.item-number {
  font-weight: 600;
  color: #67C23A;
  font-size: 15px;
}

.item-type-tag {
  font-weight: 500;
}

.order-item-details {
  background-color: white;
  border-radius: 4px;
}

:deep(.item-label) {
  font-weight: 500;
  color: #606266;
  font-size: 13px;
}

.item-type {
  font-weight: 600;
  color: #303133;
}

.frequency, .duration {
  font-weight: 500;
  color: #67C23A;
}

.item-note {
  color: #909399;
  font-style: italic;
}

.order-content {
  padding: 10px;
  background-color: #f0f9ff;
  border-radius: 4px;
  border-left: 3px solid #409EFF;
  line-height: 1.6;
  font-size: 14px;
  white-space: pre-wrap;
}

.single-order-content {
  padding: 15px;
  background-color: #fafafa;
  border-radius: 6px;
  border: 1px solid #e4e7ed;
}

.instructions {
  color: #909399;
  font-style: italic;
}

.execution-notes {
  color: #303133;
  font-style: italic;
}

.no-order-items {
  text-align: center;
  padding: 20px;
}

.notes-content {
  padding: 15px;
  background-color: #fff9e6;
  border-radius: 6px;
  border-left: 4px solid #e6a23c;
}

.notes-content p {
  margin: 0;
  line-height: 1.6;
  color: #303133;
  white-space: pre-wrap;
}

.action-section {
  text-align: right;
  padding-top: 15px;
  border-top: 1px solid #e4e7ed;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .card-header {
    flex-direction: column;
    align-items: stretch;
    gap: 15px;
  }
  
  .header-actions {
    justify-content: flex-end;
  }
  
  .breadcrumb-info {
    flex-direction: column;
    gap: 5px;
  }
  
  .medical-order-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .header-left {
    flex-wrap: wrap;
  }
  
  .header-right {
    text-align: left;
  }
}
</style> 